﻿<%@ WebHandler Language="C#" Class="APSPlanReport" %>

using System;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using ReportBusiness;
using System.Collections;
using System.IO;

/**
 * Description: APS排产查询报表
 * Copyright (c): 通力凯顿（北京）系统集成有限公司
 * Author: zhunan
 * Date: 2022.11.7
 */

public class APSPlanReport : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//查询
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getExportExcel":
                        getExportExcel(jObject);//导出
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    //查询公用sql
    string getQuerySql(JObject jObject)
    {
        string factoryid = "", workcenterid = "", teamid = "";
        JArray selectOrg = JArray.Parse(jObject["selectOrg"].ToString());
        if (selectOrg.Count == 3)
        {
            factoryid = selectOrg[0].ToString();
            workcenterid = selectOrg[1].ToString();
            teamid = selectOrg[2].ToString();
        }
        else if (selectOrg.Count == 2)
        {
            factoryid = selectOrg[0].ToString();
            workcenterid = selectOrg[1].ToString();
        }
        else
        {
            factoryid = selectOrg[0].ToString();
        }
        string sql = @"
        SELECT f.factoryname,f1.factoryname specfactoryname,w.workcentername,t.teamname,e.fullname,rd.resourcename,rd.description,cci.mfgordername,mfg.plannedstartdate,
               cci.productname,cci.productdescription,cci.containerno,
               cci.containername,cci.qty,a.workflowstepname,
               a.starttime,a.endtime,csd.checkdate,
               CASE WHEN csd.usecompleted = 1 AND csd.checkdate <= a.endtime THEN '按时完成'
                    WHEN csd.usecompleted = 1 AND csd.checkdate > a.endtime THEN '超期完成'
                    WHEN NVL(csd.usecompleted,0) = 0 AND SYSDATE <= a.endtime THEN '未完成'
                    WHEN NVL(csd.usecompleted,0) = 0 AND SYSDATE > a.endtime THEN '超期未完'
               END status,a.resstarttime,a.resendtime,
               e2.fullname planemp,
               DECODE(cno.containerstepnoshipid,NULL,NULL,'不加工') undospec,
               csd.dispatchemployeename,csd.dispatchdate
        FROM apsplandetail a
        LEFT JOIN ApsPlanDetailEmp ad ON ad.apsplandetailid = a.apsplandetailid
        LEFT JOIN containercurrentinfo cci ON cci.containerid = a.containerid
        LEFT JOIN factory f ON f.factoryid = cci.originalfactoryid
        LEFT JOIN factory f1 ON f1.factoryid = a.specfactoryid
        LEFT JOIN Workcenter w ON w.workcenterid = a.workcenterid
        LEFT JOIN team t ON t.teamid = a.teamid
        LEFT JOIN employee e ON e.employeeid = ad.employeeid
        LEFT JOIN Resourcedef rd ON rd.resourceid = a.resourceid
        LEFT JOIN mfgorder mfg ON mfg.mfgorderid = cci.mfgorderid
        LEFT JOIN containersteprecord csd ON csd.containerid = a.containerid AND csd.workflowstepid = a.workflowstepid
        LEFT JOIN employee e2 ON e2.employeeid = a.createemployeeid
        LEFT JOIN containerstepnoship cno ON cno.containerid = a.containerid AND cno.workflowstepid = a.workflowstepid AND cno.isuse = 0 AND cno.noship = 2
        WHERE 1=1 ";
        //分厂
        if (factoryid != "")
        {
            sql += string.Format("AND cci.originalfactoryid = '{0}'", factoryid);
        }

        //工序所属分厂
        if (jObject["specfactoryid"] != null && jObject["specfactoryid"].ToString() != "")
        {
            sql += string.Format("AND a.specfactoryid = '{0}'", jObject["specfactoryid"].ToString());
        }

        //下发状态
        if (jObject["apsPlanDetailStatus"] != null && jObject["apsPlanDetailStatus"].ToString() != "")
        {
            string apsPlanDetailStatus = jObject["apsPlanDetailStatus"].ToString();
            if (apsPlanDetailStatus == "未下发")
            {
                sql += " AND （a.status is null or a.status = 0） ";
            }
            else if (apsPlanDetailStatus == "下发") 
            {
                sql += " AND a.status = 1 ";
            }
        }

        //工区
        if (workcenterid != "")
        {
            sql += string.Format("AND a.workcenterid = '{0}'", workcenterid);
        }

        //班组
        if (teamid != "")
        {
            sql += string.Format("AND a.teamid = '{0}'", teamid);
        }

        //工人
        if (jObject["workerid"] != null && jObject["workerid"].ToString() != "")
        {
            sql += string.Format("AND ad.employeeid = '{0}'", jObject["workerid"].ToString());
        }

        //设备
        if (jObject["resourcename"] != null && jObject["resourcename"].ToString() != "")
        {
            sql += string.Format("AND rd.resourcename = '{0}'", jObject["resourcename"].ToString());
        }

        //订单
        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            sql += string.Format("AND cci.mfgordername = '{0}'", jObject["mfgordername"].ToString());
        }

        //件号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format("AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        //流水卡号
        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format("AND cci.containername = '{0}'", jObject["containername"].ToString());
        }

        //状态
        if (jObject["status"] != null && jObject["status"].ToString() != "")
        {
            string status = jObject["status"].ToString();
            if (status == "按时完成")
            {
                sql += " AND csd.usecompleted = 1 AND csd.checkdate <= a.endtime ";
            }
            else if (status == "超期完成")
            {
                sql += " AND csd.usecompleted = 1 AND csd.checkdate > a.endtime ";
            }
            else if (status == "未完成")
            {
                sql += " AND NVL(csd.usecompleted,0) = 0 AND SYSDATE <= a.endtime ";
            }
            else
            {
                //超期未完
                sql += " AND NVL(csd.usecompleted,0) = 0 AND SYSDATE > a.endtime ";
            }
        }

        //加工开始时间
        if (jObject["starttime"] != null && jObject["starttime"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["starttime"].ToString());
            sql += string.Format(" AND a.starttime >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss')", arr[0].ToString());
            sql += string.Format(" AND a.starttime <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss')", arr[1].ToString());
        }

        //加工结束时间
        if (jObject["endtime"] != null && jObject["endtime"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["endtime"].ToString());
            sql += string.Format(" AND a.endtime >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss')", arr[0].ToString());
            sql += string.Format(" AND a.endtime <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss')", arr[1].ToString());
        }

        //设备开始时间
        if (jObject["resstarttime"] != null && jObject["resstarttime"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["resstarttime"].ToString());
            sql += string.Format(" AND a.resstarttime >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss')", arr[0].ToString());
            sql += string.Format(" AND a.resstarttime <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss')", arr[1].ToString());
        }

        //设备结束时间
        if (jObject["resendtime"] != null && jObject["resendtime"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["resendtime"].ToString());
            sql += string.Format(" AND a.resendtime >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss')", arr[0].ToString());
            sql += string.Format(" AND a.resendtime <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss')", arr[1].ToString());
        }
        return sql;
    }

    Result getData(JObject jObject)
    {
        string sql = getQuerySql(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dtResult = dto.DBTable;
        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dtResult;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //导出
    void getExportExcel(JObject jObject)
    {
        string sql = getQuerySql(jObject);
        DataTable dtResult = dal.GetDataTable(sql);
        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        dtResult.Columns["factoryname"].Caption = "主制分厂";
        dtResult.Columns["specfactoryname"].Caption = "工序所属分厂";
        dtResult.Columns["workcentername"].Caption = "工区";
        dtResult.Columns["teamname"].Caption = "班组";
        dtResult.Columns["fullname"].Caption = "工人";
        dtResult.Columns["resourcename"].Caption = "设备编号";
        dtResult.Columns["description"].Caption = "设备名称";
        dtResult.Columns["mfgordername"].Caption = "订单号";
        dtResult.Columns["plannedstartdate"].Caption = "订单计划开始时间";
        dtResult.Columns["productname"].Caption = "件号";
        dtResult.Columns["productdescription"].Caption = "件号名称";
        dtResult.Columns["containerno"].Caption = "批次号";
        dtResult.Columns["containername"].Caption = "流水卡号";
        dtResult.Columns["qty"].Caption = "数量";
        dtResult.Columns["workflowstepname"].Caption = "工序";
        dtResult.Columns["starttime"].Caption = "加工开始时间";
        dtResult.Columns["endtime"].Caption = "加工结束时间";
        dtResult.Columns["status"].Caption = "状态";
        dtResult.Columns["checkdate"].Caption = "完工时间";
        dtResult.Columns["resstarttime"].Caption = "设备开始时间";
        dtResult.Columns["resendtime"].Caption = "设备结束时间";
        dtResult.Columns["planemp"].Caption = "排产人";
        dtResult.Columns["undospec"].Caption = "工序不加工";
        dtResult.Columns["dispatchemployeename"].Caption = "派工人";
        dtResult.Columns["dispatchdate"].Caption = "派工时间";
        ExportHelper.ExportExcel(dtResult, "APS排产查询报表导出数据");
    }
}